#include "stdafx.h"
#include "Utility.h"
#include "Game.h"
#include "Animation.h"
#include "Configs.h"
#include "Npc.h"
#include "MemTrack.h"

namespace bs
{
	Npc::Npc(Game& game)
		: game(game), dead(false), anim(NULL)
	{
	}

	Npc::~Npc()
	{
		SAFE_DELETE(this->anim);
	}

	void Npc::OnReachEdge()
	{
		this->dead = true;
	}

	bool Npc::Init(const NpcCfg& cfg, bool left, bool bullet, bool explodeAble/* = true*/)
	{
		this->fireDelay = cfg.fireDelay;
		this->fireDelayCounter = ::rand()%this->fireDelay + 100;
		this->bullet = cfg.bullet;
		this->explode = cfg.explode;
		this->explodeSnd = cfg.explodeSnd;
		this->canExplode = explodeAble;

		this->isBullet = bullet;

		if(this->isBullet)
		{
			int vx = cfg.minVx;

			if(left)
				vx = -vx;

			this->SetVel(vx, cfg.vy);
		}
		else
		{
			int vx = cfg.minVx + ::rand()%(cfg.maxVx-cfg.minVx+1);

			if(left)
				vx = -vx;

			this->SetVel(vx, 0);
		}

		int from = left ? cfg.row*cfg.col-1 : 0;
		int to = left ? 0 : cfg.row*cfg.col-1;

		this->anim = new Animation;
		this->anim->LoadFile(cfg.image.c_str(), cfg.row, cfg.col, left);
		this->anim->SetInterval(60);

		if(this->isBullet)
		{
			this->anim->SetAniSeq(from, to, 0);
			this->anim->SetStopOnEnd(true);
		}
		else
		{
			this->anim->SetAniSeq(from, to);
		}

		this->anim->SetPos(this->x, this->y);
		
		this->anim->Start();

		this->w = this->anim->GetWidth();
		this->h = this->anim->GetHeight();

		this->EnableBounds(true);
		this->EnableMoveOut(true);

		return true;
	}

	void Npc::Update(int elapse, float speedFactor)
	{
		this->DoMove(speedFactor);
		this->anim->SetPos(this->x, this->y);
		this->anim->Update(elapse, speedFactor);

		if(this->isBullet)
			return;

		this->fireDelayCounter += elapse;
		if(this->fireDelayCounter >= this->fireDelay)
		{
			this->fireDelayCounter = 0;
			this->game.AddBullet(this->bullet.c_str(), *this, this->vx<0, true);
		}
	}

	void Npc::Draw(HDC dc)
	{
		this->anim->Draw(dc);
	}

	void Npc::Die()
	{
		if(this->canExplode)
		{
			this->game.AddExplode(this->explode.c_str(), *this);
		}

		this->game.AddSound(this->explodeSnd.c_str());

		this->dead = true;
	}
}

